package com.zhangshuo.controller;

import com.zhangshuo.common.task.Schedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.ScheduledFuture;

/**
 * Created by Administrator on 2017/6/9 0009.
 */
@Controller
@RequestMapping("/schedule")
public class ScheduleController {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    /**
     * 传入参数，用来动态启动或终止任务，需要维护ID与scheduledFuture的对应关系，就可以动态删除了
     * @param id
     * @return
     */
    @RequestMapping("/start")
    @ResponseBody
    public String start(@RequestParam Integer id){
        ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule(new Schedule(id),new CronTrigger("*/5 * * * * *"));
        Schedule.scheduledFutureMap.put(id,scheduledFuture);
        return "start";
    }

    @RequestMapping("/stop")
    @ResponseBody
    public String stop(@RequestParam Integer id){
        ScheduledFuture scheduledFuture = Schedule.scheduledFutureMap.remove(id);
        if (scheduledFuture != null){
            scheduledFuture.cancel(false);
        }
        return "stop";
    }


}
